#include "simplequery.h"

#include "from.h"
#include "fromcomponent.h"
#include "select.h"
#include "where.h"
#include "groupBy.h"
#include "booleanExpression.h"

SimpleQuery::SimpleQuery(Select * select, From * from, Where * where, GroupBy * groupby, BooleanExpression * having)
{
    if(select !=NULL ) this->select = select->clone();
    else this->select = NULL;

    if(from != NULL) this->from = from->clone();
    else this->from = NULL;

    if(where != NULL) this->where = where->clone();
    else this->where = NULL;

    if(groupby != NULL) this->groupby = groupby->clone();
    else this->groupby = NULL;


    if(having != NULL) {
        BooleanExpression * h = dynamic_cast<BooleanExpression*> (having->clone());
        if (h!=NULL)this->having = h;
        else this->having=NULL;
    }
    else this->having = NULL;
}

SimpleQuery::~SimpleQuery()
{
    delete select; select = NULL;
    delete from; from = NULL;
    delete where; where = NULL;
    delete groupby; groupby = NULL;
    delete having; having = NULL;
}

SimpleQuery::SimpleQuery(const SimpleQuery & other)
{
    if(other.select !=NULL ) this->select = other.select->clone();
    else this->select = NULL;

    if(other.from != NULL) this->from = other.from->clone();
    else this->from = NULL;

    if(other.where != NULL) this->where = other.where->clone();
    else this->where = NULL;

    if(other.groupby != NULL) this->groupby = other.groupby->clone();
    else this->groupby = NULL;

    if(other.having != NULL) this->having =  dynamic_cast<BooleanExpression*> (other.having->clone());
    else this->having = NULL;
}

string SimpleQuery::toString()
{
    string str = "SELECT : ";
    if(select != NULL) str = str + select->toString();
    str = str + "\nFROM: ";
    if(from != NULL) str = str + from->toString();
    str = str + "\nWHERE : ";
    if(where != NULL) str = str + where->toString();
    str = str + "\nGROUP BY : ";
    if(groupby != NULL) str = str + groupby->toString();
    str = str + "\nHAVING : ";
    if(having != NULL) str = str + having->toString();

    return str;
}

From* SimpleQuery::getFrom() const
{
    return from;
}

void SimpleQuery::setFrom(From * from)
{
    delete this->from; this->from = NULL;
    this->from = from->clone();
}

Select* SimpleQuery::getSelect() const
{
	return select;
}

void SimpleQuery::setSelect(Select * select)
{
	delete this->select;
	this->select = select->clone();
}

Where* SimpleQuery::getWhere() const
{
	return where;
}

void SimpleQuery::setWhere(Where * where)
{
	delete this->where;
	this->where = where->clone();
}

SimpleQuery * SimpleQuery::clone()
{
    return new SimpleQuery(*this);
}



